#include <iostream>
#include <cstring>
#include <cstdlib>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

const int port = 8081;
const int num = 5;

void Usage()
{
  printf("usage: ./server port \n");
}

void *Routinue(void *arg)   //线程函数
{
    pthread_detach(pthread_self());//分离
    int fd = *(int*)arg;
    delete (int*)arg;

    //close(fd);
    while(1){
        std::cout << "thread is running: " << pthread_self() << std::endl;
        sleep(1);
    }

    return nullptr;
}

int main(int argc, char * argv[])
{
   if(argc != 2)
   {
     Usage();
     return 5; //错误代码 
   }
    int lsock = socket(AF_INET, SOCK_STREAM, 0);
    if(lsock < 0){
        std::cerr << "socket error " << std::endl;
        return 1;
    }

    int opt  = 1;
    setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    struct sockaddr_in local;
    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    //local.sin_port = htons(port);
    local.sin_port = htons(atoi(argv[1]));
    local.sin_addr.s_addr = INADDR_ANY;


    if( bind(lsock, (struct sockaddr*)&local, sizeof(local)) < 0){
        std::cerr << "bind error" << std::endl;
        return 2;
    }

    if(listen(lsock, num) < 0){
        std::cerr << "listen error" << std::endl;
        return 3;
    }

    struct sockaddr_in peer;
    for(;;){
        socklen_t len = sizeof(peer);
        int sock = accept(lsock, (struct sockaddr*)&peer, &len);
        if(sock < 0){
            std::cerr << "accept error" << std::endl;
            continue;
        }
        
        // test 1
        //std::cout << "get a new link: " << sock << std::endl;
        //int *p = new int(sock);
        //pthread_t tid;
        //pthread_create(&tid, nullptr, Routinue, p);
        //
        //
        //  test 2  send message to web and get message from web 
        char input_buf[1024*10] = {0};
        ssize_t read_size = read(sock, input_buf, sizeof(input_buf) - 1);
        if (read_size < 0) {
          return 1;
        }
        printf("[Request]: \n %s", input_buf);
        char buf[1024] = {0};
        const char* hello = "<h1>hello world</h1>";
        sprintf(buf, "HTTP/1.0 200 OK\nContent-Length:%lu\n\n%s", strlen(hello), hello);
        write(sock, buf, strlen(buf));
    }
    return 0;
}
